//
//  ChangePhoneController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/3/7.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

class ChangePhoneController: BaseViewController {
    
    var handlerClosure: (() -> Void)?
    
    private let rowVm: FamilyRowViewModel
    private let reservedPhone: String
    
    init(with vm: FamilyRowViewModel, reservedPhone: String = "") {
        self.rowVm = vm
        self.reservedPhone = reservedPhone
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private var viewModel = FamilyAddViewModel(model: FamilyAddModel()) {
        didSet {
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()
    }
    
    private var titles = [
        ["姓名", "身份证号", "地区", "详细地址", "预留手机号"],
        ["新手机号"],
        ["身份证正面", "身份证背面", "手持身份证"]
    ]
    
    private var images = [UploadImgModel(), UploadImgModel(), UploadImgModel()]
    private var currentIndex: Int = 0
    
    @IBOutlet private weak var activityView: UIActivityIndicatorView!

    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.backgroundColor = .background
            tableView.tableFooterView = UIView()
            tableView.register(ChangePhoneTextCell.nibForCell(),
                               forCellReuseIdentifier: ChangePhoneTextCell.reuseIdentifier())
            tableView.register(ChangePhoneImageCell.nibForCell(),
                               forCellReuseIdentifier: ChangePhoneImageCell.reuseIdentifier())
            tableView.register(CommonButtonCell.nibForCell(),
                               forCellReuseIdentifier: CommonButtonCell.reuseIdentifier())
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(endEditing))
            tap.cancelsTouchesInView = false
            tableView.addGestureRecognizer(tap)
        }
    }

}

extension ChangePhoneController {
    @objc private func endEditing() {
        tableView.endEditing(true)
    }
    
    func loadData() {
        activityView.startAnimating()
        FamilyAddViewModel.getFamilyMemberDetail(patientId: rowVm.relationId, success: { model in
            self.activityView.stopAnimating()
            self.viewModel = FamilyAddViewModel(model: model)
            self.viewModel.reservedPhone = self.reservedPhone
        }) { errorMsg in
            self.activityView.stopAnimating()
            HUDTool.showError(message: errorMsg)
        }
    }
}

extension ChangePhoneController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return titles.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let count = titles[section].count
        return section == 2 ? count + 1 : count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0, 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: ChangePhoneTextCell.reuseIdentifier(),
                                                     for: indexPath) as! ChangePhoneTextCell
            cell.configure(at: indexPath, titles: titles[indexPath.section], vm: viewModel)
            cell.delegate = self
            return cell
        case 2:
            if indexPath.row == 3 {
                let cell = tableView.dequeueReusableCell(withIdentifier: CommonButtonCell.reuseIdentifier(),
                                                         for: indexPath) as! CommonButtonCell
                cell.delegate = self
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: ChangePhoneImageCell.reuseIdentifier(),
                                                         for: indexPath) as! ChangePhoneImageCell
                cell.configure(at: indexPath, titles: titles[indexPath.section], imgModels: images)
                return cell
            }
        default:
            return UITableViewCell()
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0, 1: return 44
        case 2: return indexPath.row == 3 ? 90 : 204
        default: return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 16
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if indexPath.section == 2 {
            self.currentIndex = indexPath.row
            showBottomAlert()
        }
    }
}

extension ChangePhoneController: ChangePhoneTextCellDelegate, CommonButtonCellDelegate {
    func textCell(_ cell: ChangePhoneTextCell, didEndEdit text: String) {
        viewModel.newPhone = text
    }
    
    func didTappedAction(_ cell: CommonButtonCell) {
        let imgIds = self.images.compactMap { value -> String? in
            guard let noNil = value.resourceId else { return nil }
            return noNil
        }
        BindCardViewModel.changePatientPhone(patientId: rowVm.patientId, phone: viewModel.newPhone, resourceIds: imgIds.joined(separator: ",")) { (errorMsg, code) in
            switch code {
            case .failure:
                HUDTool.showError(message: errorMsg)
            case .success:
                HUDTool.show(message: "提交成功")
                self.handlerClosure?()
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
}

// MARK: - UIImagePickerControllerDelegate
extension ChangePhoneController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    private func showBottomAlert() {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

        let cancel = UIAlertAction(title:"取消", style: .cancel, handler: nil)
        let takingPictures = UIAlertAction(title:"拍照", style: .default) {
            action in
            self.goCamera()
            
        }
        let localPhoto = UIAlertAction(title:"从手机相册选择", style: .default) {
            action in
            self.goImage()
            
        }
        alert.addAction(cancel)
        alert.addAction(takingPictures)
        alert.addAction(localPhoto)
        present(alert, animated:true, completion:nil)
        
    }
    
    private func goCamera() {
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            let cameraPicker = UIImagePickerController()
            cameraPicker.delegate = self
//            cameraPicker.allowsEditing = true
            cameraPicker.sourceType = .camera
            //在需要的地方present出来
            self.present(cameraPicker, animated: true, completion: nil)
        } else {
            HUDTool.show(message: "相机权限未打开!")
        }
    }
    
    private func goImage() {
        let photoPicker =  UIImagePickerController()
        photoPicker.delegate = self
//        photoPicker.allowsEditing = true
        photoPicker.sourceType = .photoLibrary
        //在需要的地方present出来
        self.present(photoPicker, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            YSGImageUpload.upload(image: image, imageType: .medicalRecord) { code, model, error in
                switch code {
                case .success:
                    guard let model = model else {
                        HUDTool.showError(message: "图片添加失败")
                        return
                    }
                    self.images.remove(at: self.currentIndex)
                    self.images.insert(model, at: self.currentIndex)
                    self.tableView.reloadData()
                case .failure:
                    HUDTool.showError(message: error)
                }
            }
        }
        self.dismiss(animated: true, completion: nil)
    }
}
